const fs = require('fs')
const path = require('path');
const mime = require('mime')
// 可以改造成对象
// function router(pathname,res) {
//   switch (pathname) {
//     case '/login':
//       res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
//       res.write(fs.readFileSync('./static/login.html'),"utf-8")
//       break;
//     case '/home':
//       res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
//       res.write(fs.readFileSync('./static/home.html'),"utf-8")
//       break;
  
//     default:
//       res.writeHead(404,{"Content-Type":"text/html;charset=utf8"})
//       res.write(fs.readFileSync('./static/404.html'),"utf-8")
//       break;
//   }
// }

const routerObj = {
  '/login': (req,res) => {
      // res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
      // res.write(fs.readFileSync('./static/login.html'),"utf-8")
      // res.end()

      render(res,'./static/login.html')

  },
  '/':(req,res) => {
    render(res,'./static/login.html')

  },
  '/home': (req,res) => {
      // res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
      // res.write(fs.readFileSync('./static/home.html'),"utf-8")
      // res.end()
      render(res,'./static/home.html')
  },
  '/404': (req,res) => {
    if(readStaticFile(req,res)) {
      return
    }
      
      // res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
      // res.write(fs.readFileSync('./static/404.html'),"utf-8")
      // res.end()
      render(res,'./static/404.html')

  },
}

function render(res,path,type='') {
  res.writeHead(200,{"Content-Type":`${type?type:'text/html'};charset=utf8`})
  res.write(fs.readFileSync(path),'utf8')
  res.end()
}

// 静态资源管理
function readStaticFile(req,res) {
  // 获取路径
  const myURL = new URL(req.url,'http://127.0.0.1:3000')
  // path.join可以忽略不同操作系统下的‘/’兼容问题
  const pathname = path.join(__dirname,'static',myURL.pathname)
  const n = myURL.pathname.split('.')[1]
  console.log(pathname)
  if(myURL.pathname === '/') {
    return false
  }
  // existsSync 判断该路径存在吗
  if(fs.existsSync(pathname)) {
    // 根据文件的后缀,获取返回文件的头
    render(res,pathname,mime.getType(n))
    return true
  } else {
    return false
  }
}

module.exports = routerObj